﻿using UnityEditor;
using UnityEngine;

namespace Gp.Scripts.Editor
{
    [TopToolbarDrawer(order:11)]
    public class LightSwitchDrawer : ITopToolbarDrawer
    {
        private GUIContent _lightButtonContent = null;
        private GameObject _lightObject = null;

        private GameObject LightObject
        {
            get
            {
                if (_lightObject) return _lightObject;
                
                // 查找SceneLighting
                const string sceneLightName = "__SceneEditLight";
                var sceneCamera = this.GetSceneCameraTransform();
                var lights = sceneCamera.Find(sceneLightName);
                if (lights != null) return _lightObject;
                    
                lights = Resources.Load<Transform>("EditorOnly/SceneEditLight");
                if (lights)
                {
                    var obj = PrefabUtility.InstantiatePrefab(lights, sceneCamera) as Transform;
                    obj.tag = "EditorOnly";
                    obj.name = sceneLightName;
                    _lightObject = obj.gameObject;
                }
                else
                {
                    Debug.LogError("Editor-[关卡编辑工具]: SceneEditLight prefab丢失");
                    return null;
                }

                return _lightObject;
            }
        }
        private bool _isLightOn = false;

        private const string SAVE_KEY = "IS_LIGHT_SWITCH_ON";
        public LightSwitchDrawer()
        {
            var lightIcon = EditorGUIUtility.FindTexture("PointLight Gizmo");
            _lightButtonContent = new GUIContent(lightIcon, "灯光开关");
            _isLightOn = EditorPrefs.GetBool(SAVE_KEY, false);
        }

        public void OnToolbarGUI()
        {
            EditorGUIUtility.SetIconSize(new Vector2(15, 15));
            bool isLightOn = IsLightOn();
            var toggleValue = GUILayout.Toggle(isLightOn, _lightButtonContent, style:new GUIStyle("Button"));
            if (isLightOn == toggleValue) return;
            
            isLightOn = toggleValue;
            SetLight(isLightOn);
            SceneView.RepaintAll();
        }

        private bool IsLightOn()
        {
            return _isLightOn;
        }

        private void SetLight(bool status)
        {
            LightObject.SetActive(status);
            _isLightOn = status;
            EditorPrefs.SetBool(SAVE_KEY, status);
        }
    }
}